<template>
    <div class='main-talk-from'>
        <ul class="checkbox-field">
            <li class="yo-checked yo-checked-g" v-for="(item, index) in selectedCondition" :key="index" v-show="category">
                <label class="checkbox-field">
                    <div class="yo-checked yo-checked-g">
                        <input type="radio" name="codition" v-model="currentCondition" :value="item.value" />
                        <span class="type"></span>
                    </div>
                    <span>{{ item.text }}</span>
                </label>
            </li>
            <span class="back" v-show="!category" @click="showGroupTalk">x</span>
        </ul>
        <ul class='talkContent' v-show="category" @scroll="loadMore" ref="talkContent">
            <li v-for='(item, index) in talkInfo' :key='index' v-show="showItem(item.contentType)">
                <div v-if='item.from === isUser'>
                    <img :src="item.headImg">
                    <div class='message-info-left'>
                        <p>
                            <span :class='[{"wordColor": item.isEgis}]'>
                                {{item.username}}({{item.chatroomName}}){{formatTime(item.sendTime)}}
                            </span>
                            <span @click="respondPeople(item.wechatId, item.chatroom, item.username)" v-show='operateMethods({ "respond": item})'>回复Ta</span>
                            <span @click="removePeople(item)" v-show='false'>踢出Ta</span>
                            <span @click="defriend(item)" v-show='false'>拉黑Ta</span>
                            <!-- <span v-show='operateMethods({ "respond": item}) && item.isReply'>已回复</span> -->
                            <!-- <span>{{operateStatus(item)}}</span> -->
                        </p>
                        <div class="message-img" v-if="item.contentType === 2">
                            <img :src="item.content">
                        </div>
                        <div class='message-content' v-if="item.contentType !== 2">
                            {{item.content}}
                        </div>
                    </div>
                </div>
                <div v-else class='robot'>
                    <img :src="item.headImg">
                    <div class='message-info-right'>
                        <p>
                            <span :class='[{"wordColor": item.isEgis}]'>
                                {{item.username}}({{item.chatroomName}}){{formatTime(item.sendTime)}}
                            </span>
                        </p>
                        <div class='message-content'>
                            {{item.content}}
                        </div>
                    </div>
                </div>
            </li>
        </ul>
        <ul class="talkAlone" v-show="!category" ref="talkAlone">
            <li v-for='(item, index) in singleList' :key='index' v-show="showItem(item.contentType)">
                <div v-if='item.from === isUser'>
                    <img :src="item.headImg">
                    <div class='message-info-left'>
                        <p>
                            <span :class='[{"wordColor": item.isEgis}]'>
                                {{item.username}}({{item.chatroomName}}){{formatTime(item.sendTime)}}
                            </span>
                        </p>
                        <div class="message-img" v-if="item.contentType === 2">
                            <img :src="item.content">
                        </div>
                        <div class='message-content' v-if="item.contentType !== 2">
                            {{item.content}}
                        </div>
                    </div>
                </div>
                <div v-else class='robot'>
                    <img :src="item.headImg">
                    <div class='message-info-right'>
                        <p>
                            <span :class='[{"wordColor": item.isEgis}]'>
                                {{item.username}}({{item.chatroomName}}){{formatTime(item.sendTime)}}
                            </span>
                        </p>
                        <div class='message-content'>
                            {{item.content}}
                        </div>
                    </div>
                </div>
            </li>
        </ul>
        <div class='respond-message' v-show="!category">
            <ul class="talk-methods" v-show='false'>
                <li>
                    <i class="icon iconfont icon-weibiaoti22"></i>
                    <h5>图片</h5>
                </li>
                <li>
                    <i class="icon iconfont icon-libreoffice"></i>
                    <h5>文件</h5>
                </li>
                <li>
                    <el-tooltip content="top" placement="top" effect="light">
                        <div slot="content" class="quickRespond">
                            <p>rewqrweq</p>
                        </div>
                        <span>
                            <i class="icon iconfont icon-kuaisuhuifu"></i>
                            <span>快速回复</span></span>
                    </el-tooltip>
                </li>
            </ul>
            <div>
                <textarea class="message-content" @keydown.enter="sendMessage($event)" v-model.trim="messageContent"></textarea>
            </div>
        </div>
    </div>
</template>
<script>
// import { confirm } from 'umlib/common/confirm';
// import { bubble } from 'umlib/common/bubble';
// import { alert } from 'umlib/common/alert';
import { mapGetters } from 'vuex';
// import form from './form';
// import {
//     getSingleTalk,
//     postMessage
// } from '@https/associations';
// import {
//     SELECTEDCHANNEL,
// } from '@mutation/mutation-types';
export default {
    data () {
        return {
            isUser: 0,
            isBlack: 0,
            isKick: 0,
            dialogTableVisible: false,
            dialogFormVisible: false,
            formLabelWidth: '100px',
            SELECTEDCHANNEL:[1,2,3,4],
            currentCondition: 0,
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            selectedCondition: [
                {
                    value: 0,
                    text: '全部',
                    selected: false
                }, {
                    value: 1,
                    text: '图片',
                    selected: false
                }, {
                    value: 2,
                    text: '非图片',
                    selected: false
                }
            ],
            talkInfo: [],
            singleList: [],
            messageContent: '',
            leadId: 0,
            contentType: '',
            socket: '',
            category: true,
            reply: {},
            recordId: 0,
            scrollBar: true
        };
    },
    computed: {
        ...mapGetters({
            categoryList: this.SELECTEDCHANNEL,
        })
    },
    watch: {
        categoryList (v) {
            this.scrollBar = false;
            this.talkInfo = [];
            const cookies = this.getCookies();
            this.socket.send(JSON.stringify({ categoryIds: v, msgRecordType: 0, cookies }));
            this.scrollBar = true;
            this.setBottom();
        },
        currentCondition (newValue, oldValue) {
            this.currentConditionChange(newValue);
        }
    },
    methods: {
        currentConditionChange (currentCondition) {
            const cookies = this.getCookies();
            this.talkInfo.filter((messageDetail) => {
                if (currentCondition === 1) {
                    return messageDetail.contentType === 2;
                }
                return messageDetail.contentType !== 2;
            }).length < 10 ? this.socket.send(JSON.stringify({
                categoryIds: this.categoryList,
                recordId: this.recordId,
                msgRecordType: currentCondition,
                cookies
            })) : '';
        },
        loadMore () {
            if (!this.scrollBar) {
                return;
            }
            const cookies = this.getCookies();
            if (!(this.$refs.talkContent.scrollTop)) {
                this.socket.send(
                    JSON.stringify({
                        categoryIds: this.categoryList,
                        recordId: this.recordId,
                        msgRecordType: this.currentCondition,
                        cookies
                    })
                );
            }
        },
        showGroupTalk () {
            this.category = true;
            this.singleList = [];
        },
        showItem (contentType) {
            if (contentType == 2 && !(this.currentCondition !== 2)) {
                return false;
            }
            if (contentType !== 2 && !(this.currentCondition !== 1)) {
                return false;
            }
            return true;
        },
        respondPeople (wechatId, chatroom, username) {
            this.category = false;
            setTimeout(() => {
                this.$refs.talkAlone.scrollTop = this.$refs.talkAlone.scrollHeight;
            }, 1000);
            [this.reply.wechatId, this.reply.chatroom, this.reply.username] = [wechatId, chatroom, username];
            getSingleTalk({ wechatId, chatroom }).then(({ data }) => {
                this.singleList = data;
            });
        },
        removePeople (item) {
            confirm(' ', `${item.username} 已被拉黑，请务重复操作！`).then((res) => {
                bubble(`已被拉黑，请务重复操作！`);
            });
        },
        defriend (item) {
            const buttonList = [
                {
                    text: '保存',
                    action: 'confirm',
                    extraClass: 'yo-btn-light'
                },
                {
                    text: '取消',
                    action: 'close'
                }
            ];
            this.showFormDialog('', form, '', '', buttonList, item.username);
        },
        sendMessage (event) {
            if (event.keyCode === 13 && event.shiftKey) {
                return;
            }
            event.preventDefault();
            let sendContent = {
                wechatMsgType: 1,
                address: this.reply.chatroom,
                content: this.messageContent,
                addressType: 1,
                atUsernames: [this.reply.wechatId],
            };
            postMessage(sendContent).then(() => {
                this.respondPeople(this.reply.wechatId, this.reply.chatroom, this.reply.username);
                this.messageContent = '';
            });
        },
        operateStatus ({ isBlack, isKick }) {
            if (isBlack) {
                return '已拉黑';
            } else if (isKick) {
                return '已踢出';
            }
        },
        operateMethods (item) {
            const element = item[Object.keys(item)[0]];
            switch (Object.keys(item)[0]) {
                case 'isKick':
                    return !((element.isKick ? true : false) || (element.isBlack ? true : false));
                case 'isBlack':
                    return (element.isBlack ? false : true);
                default:
                    return !((element.isKick ? true : false) || (element.isBlack ? true : false));
            }
        },
        showFormDialog (contentText, form, res, css, buttonList, username) {
            let dialog = new (Vue.component('umdialog'))({
                propsData: {
                    title: contentText,
                    body: form,
                    bodyData: res,
                    buttons: buttonList || [{
                        text: '关闭',
                        action: 'close'
                    }, {
                        text: 'confirm',
                        action: 'action'
                    }]
                },
                store: this.$store,
            });
            dialog.$on('button-clicked', async function (dialog, e, action) {
                if (action === 'confirm') {
                    alert(`${username} 已被拉黑`);
                }
                dialog.$destroy(true);
            });

        },
        webSocket () {
            let url;
            if (location.host === 'test-qun.umeng100.com' || location.host === 'qun.umeng100.com') {
                url = `ws://${location.host}/qunim/im/msgRecordService`;
            } else {
                url = `ws://172.24.26.12:8082/qunim/im/msgRecordService`;
            }
            const ws = new WebSocket(url);
            const cookies = this.getCookies();
            this.socket = ws;
            ws.onopen = () => {
                ws.send(JSON.stringify({ categoryIds: this.categoryList, msgRecordType: 0, cookies }));
            };
            ws.onmessage = ({ data }) => {
                if (data !== 'heartbeat' && JSON.parse(data).length) {
                    if (JSON.parse(data)[0].source === 1) {
                        (JSON.parse(data).reverse()).forEach((message) => {
                            this.talkInfo.unshift(message);
                        });
                    } else {
                        const lastMessage = JSON.parse(data)[0];
                        this.talkInfo.push(lastMessage);
                        if (this.reply.wechatId === lastMessage.wechatId
                            && this.reply.chatroom === lastMessage.chatroom
                            && !this.category) {
                            this.singleList.push(lastMessage);
                        } else if (lastMessage.content.includes(`@${this.reply.username}`)
                            && this.reply.chatroom === lastMessage.chatroom
                            && lastMessage.from
                            && !this.category) {
                            this.singleList.push(lastMessage);
                        }
                        setTimeout(() => {
                            if (this.$refs.talkContent.scrollHeight - this.$refs.talkContent.scrollTop < 800) {
                                this.$refs.talkContent.scrollTop = this.$refs.talkContent.scrollHeight;
                            }
                            if (this.$refs.talkAlone.scrollHeight - this.$refs.talkAlone.scrollTop < 800) {
                                this.$refs.talkAlone.scrollTop = this.$refs.talkAlone.scrollHeight;
                            }
                        }, 300);
                    }
                    this.recordId = this.talkInfo[0].id;
                }
            };
            ws.onclose = () => {
                // nobody
            };
            ws.onerror = () => {
                // nobody
            };
            setTimeout(heartbeat(), 10000);
            function heartbeat () {
                setInterval(function () {
                    ws.send('heartbeat');
                }, 30000);
            }
        },
        getCookies () {
            const cookies = document.cookie.split(/;|=/);
            let cookie = {};
            let sort = 0;
            cookies.forEach((key, index) => {
                if (key.indexOf('robot_center_login_key') > -1) {
                    sort = index + 1;
                }
            });
            cookie.robot_center_login_key = cookies[sort].slice(1, -1);
            return cookie;
        },
        formatTime (time) {
            const translatedTime = Number(time);
            if (!(time > 0)) {
                return '--';
            }
            let date = new Date(translatedTime);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let hour = date.getHours();
            let minute = date.getMinutes();
            if (hour < 10) {
                hour = `0${hour}`;
            }
            if (minute < 10) {
                minute = `0${minute}`;
            }
            if (month < 10) {
                month = `0${month}`;
            }
            if (day < 10) {
                day = `0${day}`;
            }
            if (year < new Date().getFullYear()) {
                let useTime = `${year}/${month}/${day} ${hour}:${minute}`;
                return useTime;
            } else if (year == new Date().getFullYear() && month < (new Date().getMonth() + 1)) {
                let useTime = `${month}/${day} ${hour}:${minute}`;
                return useTime;
            } else if (year == new Date().getFullYear() && month == (new Date().getMonth() + 1) && day < new Date().getDate()) {
                let useTime = `${month}/${day} ${hour}:${minute}`;
                return useTime;
            } else {
                let useTime = '';
                if (hour <= 12) {
                    useTime = `上午 ${hour}:${minute}`;
                } else {
                    useTime = `下午 ${hour - 12}:${minute}`;
                }
                return useTime;
            }
        },
        setBottom () {
            setTimeout(() => {
                this.$refs.talkContent.scrollTop = this.$refs.talkContent.scrollHeight;
            }, 1000);
        }

    },
    mounted () {
        this.webSocket();
        this.setBottom();
        window.abc = this;
    },
    beforeDestroy () {
        this.socket.close();
    }
};
</script>
<style scoped>
    .talk-condition > li > .el-date-editor {
        height: 0.34rem;
        border-color: #ddddde;
    }
    .talk-condition > li > .el-date-editor:hover {
        border: 1px solid #ff9100;
    }
</style>


